package com.mxnet.chongjin.nci.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Vibrator;

import com.mxnet.chongjin.nci.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * author:chongjin
 * email:lcj270018655@163.com
 * date:2018/10/24
 * other:
 */

public class StringUtils {
    public final static int short_mil_sec = 300;
    public final static int medimu_mil_sec = 800;
    public final static int long_mil_sec = 1500;
    /**
     * 去除空格，回车，制表符
     *
     * @param str 需要去除空格的字符串
     * @return
     */
    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    public static void vibrate1(Context context, long milliseconds) {
        Vibrator vibrator = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
        vibrator.vibrate(milliseconds);//震动时长 ms
        //beep(context);
    }

    private static SoundPool mSoundPool = null;

    public static void beep(Context context) {
        if (mSoundPool == null) {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                mSoundPool = new SoundPool.Builder()
                        .setMaxStreams(3)
                        .build();
            } else {
                mSoundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);
            }
        }
        mSoundPool.load(context, R.raw.beep, Integer.MAX_VALUE);
        mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                int playId = soundPool.play(sampleId, 2.0f, 2.0f, 0, 0, 1.0f);
                //soundPool.stop(playId);
            }
        });

    }

    public static int toInt(JSONObject json, String property) throws JSONException {
        if (json.isNull(property))
            return 0;
        else
            return json.getInt(property);
    }

    public static String getNumber(SharedPreferences mPreferences, String type) {
        String deviceNo = mPreferences.getString("deviceNo", "");
        String numberKey = "number_" + type;
        String number = mPreferences.getString(numberKey, "");
        if (number.length() == 0) {
            number = deviceNo + System.currentTimeMillis() + "";
            mPreferences.edit().putString(numberKey, number).commit();
        }
        return number;

    }

    public static void clearNumber(SharedPreferences mPreferences, String type) {
        String numberKey = "number_" + type;
        mPreferences.edit().putString(numberKey, "").commit();
    }
}
